package sicnu.cs.ich.common.util;


import java.util.*;

public class CollectionUtil {

    public static boolean isEmpty(Collection collection) {
        return collection != null && !collection.isEmpty();
    }

    /**
     * 从list中随机抽取元素
     *
     * @param list
     * @param n
     * @return void
     */
    public static <T> List<T> createRandomList(List<T> list, int n) {
        // TODO 有空修改算法，使用 Shuffle 算法（效率提升应该挺客观的）
        Set<Integer> record = new HashSet<>();
        List<T> listNew = new ArrayList<>();
        if (list.size() <= n) {
            return list;
        } else {
            while (record.size() < n) {
                int random = (int) (Math.random() * list.size());
                if (!record.contains(random)) {
                    record.add(random);
                    listNew.add(list.get(random));
                }
            }
            return listNew;
        }
    }

    public static List<?> convertObjectToList(Object obj) {
        List<?> list = new ArrayList<>();
        if (obj.getClass().isArray()) {
            list = Arrays.asList((Object[]) obj);
        } else if (obj instanceof Collection) {
            list = new ArrayList<>((Collection<?>) obj);
        }
        return list;
    }
}
